import { NFormItem } from "naive-ui";
import type { FormItemProps, FormItemInst } from "naive-ui";
import type { HTMLAttributes } from "vue";
import { getSlotsDom } from "../utils";
import type { BaseComponentType } from "../types";
export type FormItemFactoryConstructorType = {
  props?: FormItemProps;
  attrs?: HTMLAttributes;
  defaultSlot?: BaseComponentType;
  feedbackSlot?: BaseComponentType;
  labelSlot?: BaseComponentType;
};
export class FormItemFactory {
  private attrs: HTMLAttributes = {};
  private props: FormItemProps = {};
  private defaultSlot: BaseComponentType = null;
  private feedbackSlot: BaseComponentType = null;
  private labelSlot: BaseComponentType = null;
  private domRef: FormItemInst | null = null;
  constructor(data?: FormItemFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.defaultSlot) this.setDefault(data.defaultSlot);
    if (data?.feedbackSlot) this.setFeedback(data.feedbackSlot);
    if (data?.labelSlot) this.setLabel(data.labelSlot);
  }
  setAttrs(attrs: HTMLAttributes) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: FormItemProps) {
    this.props = props;
    return this;
  }
  setDefault(component: BaseComponentType) {
    this.defaultSlot = component;
    return this;
  }
  setFeedback(component: BaseComponentType) {
    this.feedbackSlot = component;
    return this;
  }
  setLabel(component: BaseComponentType) {
    this.labelSlot = component;
    return this;
  }

  validate() {
    this.domRef?.validate();
  }
  restoreValidation() {
    this.domRef?.restoreValidation();
  }

  create() {
    return (
      <NFormItem
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as FormItemInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          default: () => getSlotsDom(this.defaultSlot),
          feedback: () => getSlotsDom(this.feedbackSlot),
          label: () => getSlotsDom(this.labelSlot),
        }}
      </NFormItem>
    );
  }
}
